package com.yuan.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuan.cmn.listener.DictListener;
import com.yuan.cmn.mapper.DictMapper;
import com.yuan.cmn.service.DictService;
import com.yuan.model.cmn.Dict;
import com.yuan.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 字典服务
 *
 * @Author yuan
 * @Date 2021/7/16 9:42
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    /**
     * 根据数据id查询子数据列表
     *
     * @param id
     * @return
     */
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        List<Dict> dictList = baseMapper.selectList(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id));
        //向list集合每个dict对象中设置hasChildren
        dictList.forEach(dict -> dict.setHasChildren(this.isChildren(dict.getId())));
        return dictList;
    }

    /**
     * 导出数据字典
     *
     * @param response
     */
    @Override
    public void exportDictData(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<Dict> dictList = baseMapper.selectList(null);
        List<DictEeVo> dictVoList = new ArrayList<>();
        dictList.forEach(dict -> {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict, dictEeVo);
            dictVoList.add(dictEeVo);
        });
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("dict").doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入数据字典
     *
     * @param file
     */
    @Override
    @CacheEvict(value = "dict", allEntries = true)
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据dictcode和value查询
     *
     * @param dictCode
     * @param value
     * @return
     */
    @Override
    public String getDictName(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)) {
            return baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getValue, value)).getName();
        } else {
            Dict dict = this.findDictByDictCode(dictCode);
            return baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, dict.getId()).eq(Dict::getValue, value)).getName();
        }
    }

    /**
     * 根据dictCode获取下级节点
     *
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = this.findDictByDictCode(dictCode);
        return this.findChildData(dict.getId());
    }

    /**
     * 根据dictCode获取字典
     *
     * @param dictCode
     * @return
     */
    @Override
    public Dict findDictByDictCode(String dictCode) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Dict>().eq(Dict::getDictCode, dictCode));
    }

    /**
     * 判断id下面是否有子节点
     *
     * @param id
     * @return
     */
    private boolean isChildren(Long id) {
        return baseMapper.selectCount(new LambdaQueryWrapper<Dict>().eq(Dict::getParentId, id)) > 0;
    }
}
